from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import auth
from django.http import HttpResponseRedirect

# Create your views here.
def home_main(request):
    t = get_template('../templates/account/home.tpl')
    html = t.render(Context({'current_date': 'ADMIN'}))
    return HttpResponse(html)   

def login_view(request):
    t = get_template('../templates/account/login.tpl')
    html = t.render(Context({'current_date': 'ADMIN'}))
    return HttpResponse(html)

def changePassword_view(request):
    t = get_template('../templates/account/changepassword.tpl')
    html = t.render(Context({'current_date': 'ADMIN'}))
    return HttpResponse(html)

def login_next(request):
    result = request.GET['result']
    t = get_template('../templates/account/loginresult.tpl')
    html = t.render(Context({'result': result}))
    print html
    return HttpResponse(html)

def login_auth(request):
    username = request.POST['username']
    password = request.POST['password']

    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page.
        return HttpResponse("Success to authenticate!")
    else:
        # Show an error page
        return HttpResponse("Fail to authenticate!")
    

def changepassword(request):
    result = ""
    username = request.POST['username']
    oldpassword = request.POST['old_password']
    newpassword = request.POST['new_password']
    
    try:
        user = auth.authenticate(username=username, password=oldpassword)
        if user is not None:
            user.set_password(newpassword)
            user.save()
            result = "successfully!"
        else:
            result = "password is incorrect!"
    except Exception as e:
        result = e[0]
    print result
    return HttpResponse(result)